package com.miyi.utils;
/*
 * 分页工具
 */
public class Page {
	
	public  long MAX_ROW = 10;
	private long index;
	private long page_num;
	private long total;
	private String url;
	
	/**
	 * 分页工具
	 * @param index offset起始位置
	 * @param total 总记录数
	 * @param page_size 每页显示记录数
	 * @param url 分页请求地址
	 */
	public Page(long index, long total,long page_size, String url) {
		this.index = index;
		this.total = total;
		this.MAX_ROW = page_size;
		this.url = url;
		this.page_num = total%MAX_ROW==0? total/MAX_ROW : total/MAX_ROW+1;
	} 

	public String getFooter() {
		//不足一页 不显示分页信息
		if(total<=MAX_ROW) {
			return "";
		} 
		StringBuffer sb = new StringBuffer("分页:");
		//不足MAX_ROW页
		if(page_num <= MAX_ROW) {
			for(int i=0; i<page_num; i++) {
				insertTag(sb, i);
			}
			if(index+MAX_ROW < total) {
			insertTag(sb, index+MAX_ROW, "下一页");
			} else {
				sb.append("下一页");
			}
			return sb.toString();
		} else {
			long unit = MAX_ROW * MAX_ROW;
			if(index < unit) {
				int i;
				for(i=0; i<MAX_ROW; i++) {
					insertTag(sb, i);
				}
				String tt = "下" + MAX_ROW + "页";
				insertTag(sb, i*MAX_ROW, tt);
				return sb.toString();
			} else {
				//当前页
				long currentPage = index/MAX_ROW;
				//当前面 一面有MAX_ROW页
				long currentSection = currentPage/MAX_ROW + 1;
				//上一面起始页
				long lastPage = (currentSection-1) * MAX_ROW - 1;
				//上一面起始记录
				long lastPageRow = lastPage * MAX_ROW;
				//下一面起始页
				long nextPage = currentSection * MAX_ROW;
				//下一面起始记录
				long nextPageRow = nextPage * MAX_ROW;
				String tt = "上" + MAX_ROW + "页";

				insertTag(sb, lastPageRow, tt);
				//是否显示下一面
				if(nextPageRow <= total-1) {
					for(int i=0; i<MAX_ROW; i++) {
						insertTag(sb, i+lastPage + 1);
					}
					tt = "下" + MAX_ROW + "页";
					insertTag(sb, nextPageRow, tt);
				} else {
					long lengthOfPage = total - (lastPage + 1) * MAX_ROW;
					lengthOfPage = lengthOfPage/MAX_ROW + 1;
					for(int i=0; i<lengthOfPage; i++) {
						insertTag(sb, i - 1 + lastPage);
					}
				}
				return sb.toString();
			}
		}
	}

	public void insertTag(StringBuffer sb, long num) {
		long temp = index/MAX_ROW;
		if(num==temp) {
			sb.append(num+1).append("  ");
		} else {
			sb.append("<a href=" + url + "start_index=");
			sb.append(num*MAX_ROW).append(">").append(num+1).append("</a>  ");
		}
	}

	public void insertTag(StringBuffer sb, long num, String str) {
		sb.append("<a href=" + url + "start_index=");
		sb.append(num).append(">").append(str).append("</a>  ");
	}

//	public static void main(String[] args) {
//		System.out.println(new Page(120,250,"http://www.g.cn").getFooter());
//		//输出:   分页:上10页 11 12 13 14 15 16 17 18 19 20 下10页
//	}
}
